package be.webchess.www.actions;

import java.io.IOException;

import javax.servlet.http.HttpSession;

import be.webchess.www.model.User;
import be.webchess.www.service.IUserService;
import be.webchess.www.service.impl.UserService;
import be.webchess.www.utils.MessageDigestHelper;


public class SDoLoginAction extends BaseAction {
	
	IUserService us;
	User user;
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6200503551937150452L;

	public String execute (){
		
		try {
			user = new User();
			
			if ( request.getParameter("login") == null )
			{
				this.addActionError("Login miss");
				return ERROR;
			}
			
			us = new UserService(connection);
			
			user.setLogin(request.getParameter("login"));
			user.setPassword( MessageDigestHelper.sha1(request.getParameter("pass")) );
			
			if ( !us.doLogin(user) )
			{
				this.addActionError("Login error");
				return ERROR;
			}
						
			user = us.findByUsername(request.getParameter("login"));
			HttpSession sess =request.getSession(true);
			sess.setAttribute("loggedUser",user);
			
  
		} catch ( Exception ex )
		{
			this.addActionError(ex.getMessage());
			return ERROR;
		}
		
		String red = "/WebChess/home";
		try {
			response.sendRedirect(red);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return SUCCESS;
	}

	@Override
	public String getTitle() {
		// TODO Auto-generated method stub
		return "Login";
	}

	@Override
	public String getContent() {
		// TODO Auto-generated method stub
		return "";
	}

	@Override
	public String getErrorTitle() {
		// TODO Auto-generated method stub
		return "LOGIN ERROR";
	}

	@Override
	public String getHeadExtra() {
		// TODO Auto-generated method stub
		return "";
	}

}
